<template>
  <div>
    <el-container>
      <el-aside width="230px">
        <!-- <div class="plr-4"> -->
        <div class="app_card mb-2 pt-4  pb-4" style="height:calc(100vh - 180px);overflow-y: scroll;padding:0">
          <el-menu unique-opened  :default-active="queryParam.floorId"  @open="openMenu" @close="closeMenu" @select="onSelectFloor">
            <el-sub-menu index="0" @click.stop="null">
              <template #title>主校区</template>
                  <template v-for="(item, idx) of bildingList">
                    <el-sub-menu :index="'20000'+item.buildingCode.toString()" >
                      <template #title>
                        {{ item.name }}
                      </template>
                      <template v-if="item.id === queryParam.buildingId" v-for="(_item,_idx) of floorList">
                        <el-menu-item :index="[_item.id].join('')" :class="queryParam.floorId == _item.id ? 'is-active' : ''" >{{_item.floor}}</el-menu-item>
                      </template>
                    </el-sub-menu>
                  </template>
            </el-sub-menu>
          </el-menu>
        </div>
        <!-- </div> -->
      </el-aside>
      <el-main v-show="!showRoom">
        <div class="app_card mb-2 pt-4  pb-4">
          <!-- 权限 -->
          <div class="d-flex justify-content-between align-items-center">
            <div class="flex-grow-1">
              <!-- {{queryParam.radio_floor}} ApiUrls.buildingfloor, { id: _id }-->
              <el-radio-group class="radio_button" v-model="queryParam.radio_floor" @change="radioFloorChange">
                <el-radio-button label="-1">全部</el-radio-button>
                <el-radio-button label="-2">上课中</el-radio-button>
                <el-radio-button label="-4">空闲中</el-radio-button>
                <el-radio-button label="-3">维护中</el-radio-button>
                <!-- 此处修改：&& radioIcon != '3' -->
<!--                <el-radio-button v-show="radioSelect == '2' && radioIcon != '3'" v-for="item in floorList" :key="item.id"-->
<!--                  :label="item.id">{{-->
<!--                    item.floor }}</el-radio-button>-->

              </el-radio-group>

              <template v-if="radioIcon == '3'">
                &emsp;
                <el-checkbox v-if="listContent > 0" class="v-m mr-3 pt-2" v-model="checkedSelected"
                  @change="controlSelect">全选</el-checkbox>
                <template v-if="checkedSelected">
                  <el-button class="class_btn" type="primary" plain @click="onClass(2)">上课</el-button>
                  <el-button class="class_btn" type="primary" plain @click="onClass(1)">下课</el-button>
                  <template v-if="queryParam.radio_floor == '-1'">
                    <el-button class="class_btn" type="primary" plain @click="onLight(2)">一键开灯</el-button>
                    <el-button class="class_btn" type="primary" plain @click="onLight(1)">一键关灯</el-button>
                  </template>
                </template>
              </template>

            </div>
            <div class="d-flex">
              <el-radio-group v-model="radioIcon" @change="switchIcon">
                <el-radio label="1">大图</el-radio>
                <el-radio label="2">小图</el-radio>
                <el-radio label="3">列表控制</el-radio>


              </el-radio-group>
              <!-- <el-radio-group v-model="radioSelect" @change="switchSelect">
                  <el-radio label="1">列表控制</el-radio>

                  <el-radio label="2">面板控制</el-radio>
                  <el-radio label="3">物联控制</el-radio>
                </el-radio-group> -->
            </div>
          </div>
        </div>

        <!-- 列表控制 -->
        <!-- <ListControl v-show="radioSelect == '1'" ref="listControlRef" @goIot="goIot" @setListContent="setListContent">
          </ListControl> -->
        <ListControl v-show="radioIcon == '3'" @onSelection="onChangeListControl" ref="listControlRef" @goRoom="goRoom" @setListContent="setListContent">
        </ListControl>
        <!-- 面板控制 -->
        <PanelControl v-show="radioSelect == '2' && radioIcon != '3'" ref="panelControlRef" :bildingDto="bildingDto"
          @goRoom="goRoom">
        </PanelControl>
        <!-- 物联控制 -->
        <IoTInformation v-show="radioSelect == '3'" ref="ioTInformationRef" @goRoom="goRoom"></IoTInformation>
      </el-main>
      <!-- 教室详情 -->
      <el-main v-show="showRoom">
        <ClassroomDetails ref="classroomDetailsRef" @goClass="goClass"></ClassroomDetails>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
/**
 * 教室管理
 */
import { ref, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import useAuthStore from '@/stores/useAuthStore';
import { ElLoading } from 'element-plus'

//组件
import useBuildingStore from '@/stores/useBuildingStore';

import ListControl from './ListControl.vue';
import IoTInformation from './IoTInformation.vue';
import PanelControl from './PanelControl.vue';
import ClassroomDetails from './ClassroomDetails.vue';
import { number } from 'echarts';
const buildingStore = useBuildingStore();
// ======================================================
//                      变量声明
// ======================================================
// const buildingId = ref(null);
const checkedSelected = ref(false)

const bildingDto = ref(null)
const bildingList = ref([]);
const floorList = ref([]);
function getBuildList(tree = false) {
  const loadingInstance = ElLoading.service({ text: '加载中...' })
  EsAjax.post(ApiUrls.buildingAll, {}).then(res => {
    if (res.data.data && res.data.data.length) {
      bildingList.value = (res.data.data || []).map((item,idx)=>{
        item.level = 1
        return item
      });
      // queryParam.value.buildingId = `${bildingList.value[0].id}`
      // bildingDto.value = bildingList.value[0]
      // loadData();
      // initFloor(queryParam.value.buildingId)
    }
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loadingInstance.close()
  })
}


// 点击一级目录
const handleSelect = (key) => {
  queryParam.value.buildingId = key.toString();
  let obj = bildingList.value.find(item => item.id == key)
  if (obj) {
    bildingDto.value = obj
  }
  showRoom.value = false

  // initFloor(queryParam.value.buildingId)
};
const initFloor = (_id) => {
  queryParam.value.radio_floor = '-1'
  queryParam.value.floorId = ''
  EsAjax.post(ApiUrls.buildingfloor, { id: Number(_id) }).then(res => {
    console.log('buildingfloor===', res)
    if (res.data.code && res.data.code === 200) {
      floorList.value = (res.data.data || []).sort((a,b)=>a.sort - b.sort)
      // if (res.data.data && res.data.data.length) {
      //   queryParam.value.radio_floor = res.data.data[0].id
      //   queryParam.value.floorId = res.data.data[0].id
      //   floorChange();
      // }

    }
  })
}

const authStore = useAuthStore();
// 组件引用
const classroomDetailsRef = ref(null);
const listControlRef = ref(null);
const panelControlRef = ref(null);
const ioTInformationRef = ref(null);
// 教室分组数据
const dataOfGroups = ref([]);
const defaultProps = {
  children: 'children',
  label: 'label',
}

// 表格查询参数
const queryParam = ref({
  radio_floor: '-1',
  button_type: null,
  class_id: null,//选中教室id
  radio_icon: '1',//大图小图
  floorId: '',
})
// 分页栏配置数据
const showRoom = ref(false);
const radioFloor = ref('-1');
const buttonType = ref('-2');
const radioIcon = ref('3');
const radioSelect = ref('2');
//列表控制数量
const listContent = ref(0);

// ======================================================
//                      点击操作
// ======================================================
const controlSelect = (e) => {
  // console.log('全选', e)
  listControlRef.value.onAllSelection(e)
}
const onSelectFloor = (ev)=>{
  queryParam.value.floorId = ev
  radioFloorChange()

}
const radioFloorChange = () => {
  checkedSelected.value = false
  // if (Number(val) > 0) {
  //   queryParam.value.floorId = val
  // } else {
  //   queryParam.value.floorId = ''
  // }
  // if(Number(val))
  loadData();
}
const onChangeListControl= (list)=>{
  if(list.length > 0){
    checkedSelected.value = true
    listContent.value = list.length
  }else{
    checkedSelected.value = false
  }

}
const openMenu = (idx)=>{
  console.log(idx)
  if(/^20000/.test(idx)){
    const obj = bildingList.value.find(item=>{
      return item.buildingCode === idx.replace('20000','')
    })
    bildingDto.value = obj
    queryParam.value.buildingId = obj.id
    queryParam.value.floorId = null
    console.log(obj.id)
    initFloor(obj.id)
    obj.isActive = true
  }

}
const closeMenu = (idx)=>{
  if(/^2-/.test(idx)){
    floorList.value = []
    queryParam.value.buildingId = null
    queryParam.value.floorId = null
  }

}
const floorChange = () => {
  loadData();
}
const buttonTypeChange = () => {
  if (radioFloor.value == "-2") {//上课
  } else if (radioFloor.value == "-1") {//下课
  } else {

  }

}
const switchIcon = () => {
  loadData();

}
const goIot = () => {
  radioSelect.value = '3'
  loadData();
}
const goRoom = (row) => {
  showRoom.value = true
  localStorage.setItem("ROOM_DATA", JSON.stringify(row));
  classroomDetailsRef.value.loadData(row);
}
const goClass = (row) => {
  console.log(row, '666');
  showRoom.value = false
}

//切换教室模式
const switchSelect = () => {
  loadData();
}


// 点击分组树形节点
const onClickNode = (data) => {
  // console.log('点击树形节点', data)
  queryParam.value.class_id = data.id;
  loadData();

}



// ======================================================
//                      处理事件
// ======================================================

const loadTreeData = () => {
  EsAjax.post(ApiUrls.roomData).then(res => {
    // console.error('res====', res)
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    dataOfGroups.value = res.data.data;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}
const loadData = () => {
  // console.error('queryParam===', queryParam.value)
  queryParam.value.radio_icon = radioIcon.value
  if (radioIcon.value == '3') {//列表控制
    listControlRef.value.onRefresh(queryParam.value);
  } else if (radioSelect.value == '2') {//面板控制
    panelControlRef.value.onRefresh(queryParam.value);
  } else if (radioSelect.value == '3') {//物联控制
    ioTInformationRef.value.onRefresh(queryParam.value);
  }
}
//列表控制数量  大于0再显示全选
const setListContent = (val) => {
  listContent.value = val
}

// * value 2开  1关
const onLight = (value) => {
  var data = {
    buildingId: Number(queryParam.value.buildingId),
    type: 1,
    floorId: 0,
    value: value,
  };
  let text = value == 2 ? '开' : '关'
  // console.log('text==', text)
  const loadingInstance = ElLoading.service({ text: text + '灯中...' })
  EsAjax.post(ApiUrls.remoteLight, data).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(`一键${text}灯失败！`);
    } else {
      ElMessage.success(`一键${text}灯成功！`);

    }
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loadingInstance.close()
  })

}
//全部 value 下课 1 上课2
const onClass = (value) => {
  let data = {
    buildingId: Number(queryParam.value.buildingId),
    floorId: 0,
    value: value,
    type: null,
  };
  if (queryParam.radio_floor == '-1') {
    data.type = 1
  }
  if (queryParam.radio_floor == '-2') {
    data.type = 2

  }
  if (queryParam.radio_floor == '-3') {
    data.type = 3
  }

  let text = value == 2 ? '上' : '下'
  // console.log('text==', text)
  const loadingInstance = ElLoading.service({ text: text + '课中...' })
  EsAjax.post(ApiUrls.remoteLight, data).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(`一键${text}课失败！`);
    } else {
      ElMessage.success(`一键${text}课成功！`);

    }
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loadingInstance.close()
  })


}





onMounted(() => {
  //加载大楼数据
  getBuildList()
})


</script>
<style lang="less">
.class_btn {
  margin-top: 2px;
  height: 28px;
}

// vertical-align: middle;
.el-menu-item {
  font-size: 16px;
}
</style>

